﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Bio.Data.Providers
{
    public static class StreamExtensions
    {
        /// <summary>
        /// Simple extension to read a set of lines.
        /// </summary>
        /// <param name="sr"></param>
        /// <returns></returns>
        public static IEnumerable<string> Lines(this StreamReader sr)
        {
            if (sr == null)
                throw new ArgumentNullException("sr");
            string line;
            while ((line = sr.ReadLine()) != null && line.Length>0 && line[0] != '\0')
                yield return line;
        }

        /// <summary>
        /// Reads a line from the memory stream - used when parsing positions for the virtualized file.
        /// </summary>
        /// <param name="fs"></param>
        /// <returns></returns>
        public static string ReadLine(this Stream fs)
        {
            StringBuilder sb = new StringBuilder();
            for (; ; )
            {
                int ch = fs.ReadByte();
                if (ch <= 0 || ch == 0xd || ch == 0xa)
                    break;

                sb.Append((char)ch);
            }

            return sb.ToString();
        }

        /// <summary>
        /// Pads a stream out with a given character for a specific length
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="P"></typeparam>
        /// <param name="stream"></param>
        /// <param name="pad"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public static IEnumerable<T> PadRight<T>(this IEnumerable<T> stream, T pad, int totalCount)
        {
            int count = 0;
            foreach (var item in stream)
            {
                count++;
                yield return item;
            }
            for (int i = 0; i < totalCount-count; i++)
                yield return pad;
        }
    }
}
